package com.yaodian100.ec.generatepage.web;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.generate.entity.GenerateAdvertise;
import com.yaodian100.ec.generate.entity.GenerateContent;
import com.yaodian100.ec.generate.entity.GeneratePosition;
import com.yaodian100.ec.generate.service.GenerateService;
import com.yaodian100.ec.generate.service.impl.IdxWeeklyRecommendAdvGenerater;
import com.yaodian100.ec.generatepage.entity.IdxWeeklyRecommendAdv;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.service.ProductService;

public class IdxWeeklyRecommendAdvAction extends AbstractAdvAction {

	private static final String PROPERTY_NAME_TOPICAL_AD_CODE3 = "topicalAdCode3";
	private static final String PROPERTY_NAME_TOPICAL_AD_CODE2 = "topicalAdCode2";
	private static final String PROPERTY_NAME_TOPICAL_AD_CODE1 = "topicalAdCode1";
	private static final String PROPERTY_NAME_FRESH_AD_CODE3 = "freshAdCode3";
	private static final String PROPERTY_NAME_FRESH_AD_CODE2 = "freshAdCode2";
	private static final String PROPERTY_NAME_FRESH_AD_CODE1 = "freshAdCode1";
	private static final String PROPERTY_NAME_RECOMMEND_AD_CODE3 = "recommendAdCode3";
	private static final String PROPERTY_NAME_RECOMMEND_AD_CODE2 = "recommendAdCode2";
	private static final String PROPERTY_NAME_RECOMMEND_AD_CODE1 = "recommendAdCode1";
	private static final String PROPERTY_NAME_TOPICAL_PRODUCT_ID3 = "topicalProductId3";
	private static final String PROPERTY_NAME_TOPICAL_PRODUCT_ID2 = "topicalProductId2";
	private static final String PROPERTY_NAME_TOPICAL_PRODUCT_ID1 = "topicalProductId1";
	private static final String PROPERTY_NAME_FRESH_PRODUCT_ID3 = "freshProductId3";
	private static final String PROPERTY_NAME_FRESH_PRODUCT_ID2 = "freshProductId2";
	private static final String PROPERTY_NAME_FRESH_PRODUCT_ID1 = "freshProductId1";
	private static final String PROPERTY_NAME_RECOMMEND_PRODUCT_ID3 = "recommendProductId3";
	private static final String PROPERTY_NAME_RECOMMEND_PRODUCT_ID2 = "recommendProductId2";
	private static final String PROPERTY_NAME_RECOMMEND_PRODUCT_ID1 = "recommendProductId1";
	private static final String FIELD_NAME_END_TIME = "weeklyRecommendAdv.endTime";
	private static final String FIELD_NAME_START_TIME = "weeklyRecommendAdv.startTime";

	private static final long serialVersionUID = 1L;

	private IdxWeeklyRecommendAdv idxWeeklyRecommendAdv;

	@Autowired
	private ProductService productService;
	@Autowired
	private GenerateService generateService;

	public String newWeeklyRecommendAdv() {
		return INPUT;
	}

	public String editWeeklyRecommendAdv() throws IOException {
		Long advId = getAdvId();
		if (advId == null) {
			advId = getAdv().getId();
		}
		GenerateAdvertise targetAdv = this.generateService.get(advId);
		GenerateContent targetAdvContent = this.generateService.getGenerateContentByAdvId(advId).get(0);

		if (targetAdv == null) {
			return LIST_IDX_ADV;
		}

		setAdv(targetAdv);
		setIdxWeeklyRecommendAdv(new IdxWeeklyRecommendAdv());

		DateFormat dateFormatter = new SimpleDateFormat(EcConstant.PATTERN_DATE);
		DateFormat timeFormatter = new SimpleDateFormat("HH:mm");
		String startDateString = dateFormatter.format(getAdv().getStartDate());
		String startTimeString = timeFormatter.format(getAdv().getStartDate());
		String endDateString = dateFormatter.format(getAdv().getEndDate());
		String endTimeString = dateFormatter.format(getAdv().getEndDate());
		getIdxWeeklyRecommendAdv().setStartDate(startDateString);
		getIdxWeeklyRecommendAdv().setStartTime(startTimeString);
		getIdxWeeklyRecommendAdv().setEndDate(endDateString);
		getIdxWeeklyRecommendAdv().setEndTime(endTimeString);

		Properties properties = new Properties();
		Reader reader = new StringReader(targetAdvContent.getContents());
		properties.load(reader);

		getIdxWeeklyRecommendAdv().setRecommendProductId1(properties.getProperty(PROPERTY_NAME_RECOMMEND_PRODUCT_ID1));
		getIdxWeeklyRecommendAdv().setRecommendProductId2(properties.getProperty(PROPERTY_NAME_RECOMMEND_PRODUCT_ID2));
		getIdxWeeklyRecommendAdv().setRecommendProductId3(properties.getProperty(PROPERTY_NAME_RECOMMEND_PRODUCT_ID3));
		getIdxWeeklyRecommendAdv().setRecommendAdCode1(properties.getProperty(PROPERTY_NAME_RECOMMEND_AD_CODE1));
		getIdxWeeklyRecommendAdv().setRecommendAdCode2(properties.getProperty(PROPERTY_NAME_RECOMMEND_AD_CODE2));
		getIdxWeeklyRecommendAdv().setRecommendAdCode3(properties.getProperty(PROPERTY_NAME_RECOMMEND_AD_CODE3));

		getIdxWeeklyRecommendAdv().setFreshAdCode1(properties.getProperty(PROPERTY_NAME_FRESH_AD_CODE1));
		getIdxWeeklyRecommendAdv().setFreshAdCode2(properties.getProperty(PROPERTY_NAME_FRESH_AD_CODE2));
		getIdxWeeklyRecommendAdv().setFreshAdCode3(properties.getProperty(PROPERTY_NAME_FRESH_AD_CODE3));
		getIdxWeeklyRecommendAdv().setFreshProductId1(properties.getProperty(PROPERTY_NAME_FRESH_PRODUCT_ID1));
		getIdxWeeklyRecommendAdv().setFreshProductId2(properties.getProperty(PROPERTY_NAME_FRESH_PRODUCT_ID2));
		getIdxWeeklyRecommendAdv().setFreshProductId3(properties.getProperty(PROPERTY_NAME_FRESH_PRODUCT_ID3));

		getIdxWeeklyRecommendAdv().setTopicalProductId1(properties.getProperty(PROPERTY_NAME_TOPICAL_PRODUCT_ID1));
		getIdxWeeklyRecommendAdv().setTopicalProductId2(properties.getProperty(PROPERTY_NAME_TOPICAL_PRODUCT_ID2));
		getIdxWeeklyRecommendAdv().setTopicalProductId3(properties.getProperty(PROPERTY_NAME_TOPICAL_PRODUCT_ID3));
		getIdxWeeklyRecommendAdv().setTopicalAdCode1(properties.getProperty(PROPERTY_NAME_TOPICAL_AD_CODE1));
		getIdxWeeklyRecommendAdv().setTopicalAdCode2(properties.getProperty(PROPERTY_NAME_TOPICAL_AD_CODE2));
		getIdxWeeklyRecommendAdv().setTopicalAdCode3(properties.getProperty(PROPERTY_NAME_TOPICAL_AD_CODE3));

		return INPUT;
	}

	public String saveWeeklyRecommendAdv() throws Exception {

		StringBuffer contentBuffer = new StringBuffer();
		GenerateContent advertiseContent;
		GeneratePosition generatePosition;

		getAdv().setAdvType(IdxWeeklyRecommendAdvGenerater.ADV_TYPE_IDX_WEEKLYRECOMMEND);

		Long advertiseId = getAdv().getId();
		if (getAdv().getId() == null) {
			advertiseContent = new GenerateContent();
			generatePosition = new GeneratePosition();
		} else {
			advertiseContent = this.generateService.getGenerateContentByAdvId(advertiseId).get(0);
			generatePosition = this.generateService.getGeneratePositionByAdvId(advertiseId).get(0);
		}

		if (StringUtils.isBlank(getAdv().getAdvName())) {
			addFieldError("idxWeeklyRecommendAdv.name", "广告名称不可空白");
		}

		// 起迄日期
		String timePattern = EcConstant.PATTERN_TIMESTAMP_HH_MM;
		DateFormat formatter = new SimpleDateFormat(timePattern);

		String startDateString = this.idxWeeklyRecommendAdv.getStartDate();
		String startTimeString = this.idxWeeklyRecommendAdv.getStartTime();
		if (startDateString != null) {
			if (startTimeString == null) {
				startTimeString = "00:00";
			}
			String startTimePointString = startDateString + " " + startTimeString;
			try {
				Date startTimePoint = formatter.parse(startTimePointString);
				getAdv().setStartDate(startTimePoint);
			} catch (ParseException e) {
				addFieldError(FIELD_NAME_START_TIME, "起始日期或时间格式不正碉");
			}
		}

		String endDateString = this.idxWeeklyRecommendAdv.getEndDate();
		String endTimeString = this.idxWeeklyRecommendAdv.getEndTime();
		String endTimePointString = endDateString + " " + endTimeString;
		if (endDateString != null) {
			if (endTimeString == null) {
				endTimeString = "23:59";
			}
			try {
				Date endTimePoint = formatter.parse(endTimePointString);
				getAdv().setEndDate(endTimePoint);
			} catch (ParseException e) {
				addFieldError(FIELD_NAME_END_TIME, "结束日期或时间格式不正碉");
			}
		}

		String recommendProductId1 = this.idxWeeklyRecommendAdv.getRecommendProductId1();
		String recommendProductId2 = this.idxWeeklyRecommendAdv.getRecommendProductId2();
		String recommendProductId3 = this.idxWeeklyRecommendAdv.getRecommendProductId3();
		String freshProductId1 = this.idxWeeklyRecommendAdv.getFreshProductId1();
		String freshProductId2 = this.idxWeeklyRecommendAdv.getFreshProductId2();
		String freshProductId3 = this.idxWeeklyRecommendAdv.getFreshProductId3();
		String topicalProductId1 = this.idxWeeklyRecommendAdv.getTopicalProductId1();
		String topicalProductId2 = this.idxWeeklyRecommendAdv.getTopicalProductId2();
		String topicalProductId3 = this.idxWeeklyRecommendAdv.getTopicalProductId3();

		// 檢核商品代號
		validateProductId(recommendProductId1, "recommendProductId1", "本周推荐的商品编号一查无商品");
		validateProductId(recommendProductId2, "recommendProductId2", "本周推荐的商品编号二查无商品");
		validateProductId(recommendProductId3, "recommendProductId3", "本周推荐的商品编号三查无商品");
		validateProductId(freshProductId1, "freshProductId1", "新鲜货的商品编号一查无商品");
		validateProductId(freshProductId2, "freshProductId2", "新鲜货的商品编号二查无商品");
		validateProductId(freshProductId3, "freshProductId3", "新鲜货的商品编号三查无商品");
		validateProductId(topicalProductId1, "topicalProductId1", "本月话题的商品编号一查无商品");
		validateProductId(topicalProductId2, "topicalProductId2", "本月话题的商品编号二查无商品");
		validateProductId(topicalProductId3, "topicalProductId3", "本月话题的商品编号三查无商品");

		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_RECOMMEND_PRODUCT_ID1, recommendProductId1);
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_RECOMMEND_PRODUCT_ID2, recommendProductId2);
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_RECOMMEND_PRODUCT_ID3, recommendProductId3);
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_FRESH_PRODUCT_ID1, freshProductId1);
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_FRESH_PRODUCT_ID2, freshProductId2);
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_FRESH_PRODUCT_ID3, freshProductId3);
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_TOPICAL_PRODUCT_ID1, topicalProductId1);
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_TOPICAL_PRODUCT_ID2, topicalProductId2);
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_TOPICAL_PRODUCT_ID3, topicalProductId3);

		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_RECOMMEND_AD_CODE1,
				this.idxWeeklyRecommendAdv.getRecommendAdCode1());
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_RECOMMEND_AD_CODE2,
				this.idxWeeklyRecommendAdv.getRecommendAdCode2());
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_RECOMMEND_AD_CODE3,
				this.idxWeeklyRecommendAdv.getRecommendAdCode3());
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_FRESH_AD_CODE1,
				this.idxWeeklyRecommendAdv.getFreshAdCode1());
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_FRESH_AD_CODE2,
				this.idxWeeklyRecommendAdv.getFreshAdCode2());
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_FRESH_AD_CODE3,
				this.idxWeeklyRecommendAdv.getFreshAdCode3());
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_TOPICAL_AD_CODE1,
				this.idxWeeklyRecommendAdv.getTopicalAdCode1());
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_TOPICAL_AD_CODE2,
				this.idxWeeklyRecommendAdv.getTopicalAdCode2());
		appendPropertyAndLineBreakToContentBuffer(contentBuffer, PROPERTY_NAME_TOPICAL_AD_CODE3,
				this.idxWeeklyRecommendAdv.getTopicalAdCode3());

		if (!hasErrors()) {
			// 寫入db
			advertiseContent.setContents(contentBuffer.toString());
			if (getAdv().getId() == null) {
				this.generateService.saveGenerateCombine(getAdv(), generatePosition, advertiseContent);
			} else {
				GenerateAdvertise advInDb = this.generateService.get(advertiseId);
				BeanUtils.copyProperties(getAdv(), advInDb, baseEntityPropertiesNames);
				this.generateService.updateGenerateCombine(getAdv(), generatePosition, advertiseContent);
			}

			try {
				this.generateService.generateIdxWeeklyRecommendAdv();
			} catch (IOException e) {
				addActionMessage("重新產生檔案失敗");
			}

			addActionMessage("储存成功");
		}
		return RESULT_VIEW;
	}

	public String displaySavedAdv() throws IOException {
		addActionMessage("储存成功");
		return editWeeklyRecommendAdv();
	}

	private void validateProductId(String recommendProductId1, String fieldName, String errorMessage) {
		Product product = this.productService.get(recommendProductId1);
		if (product == null) {
			addFieldError(fieldName, errorMessage);
		}
	}

	public IdxWeeklyRecommendAdv getIdxWeeklyRecommendAdv() {
		return this.idxWeeklyRecommendAdv;
	}

	public void setIdxWeeklyRecommendAdv(IdxWeeklyRecommendAdv idxWeeklyRecommendAdv) {
		this.idxWeeklyRecommendAdv = idxWeeklyRecommendAdv;
	}

	public ProductService getProductService() {
		return this.productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public GenerateService getGenerateService() {
		return this.generateService;
	}

	public void setGenerateService(GenerateService generateService) {
		this.generateService = generateService;
	}
}
